package com.chen.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.chen.vo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author cws
 * @since
 */
@RestController
@RequestMapping("/oss")
public class UploadController {

    @PostMapping(value = "/upload",produces = "application/json")
    public Result upload(MultipartFile multipartFile) {
        //这里根据自己的参数设置 oss-cn-beijing.aliyuncs.com
        String endpoint = "oss-cn-guangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5tHsx48VZ6deaSYPLHtB";
        String accessKeySecret = "UHGhMtI3NZg0SYUllmLFHiWoLlJPDr";
        String bucketName = "order-ly";

        // 创建OSSClient实例
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //设置文件路径，根据日期区分文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(new Date());
        //拼接上传路径
        originalFilename = "order-ly/" + date + "/" + originalFilename;
        //上传
        oss.putObject(bucketName, originalFilename, inputStream);
        //返回上传的文件的访问地址
        String url = "https://" + bucketName + "." + endpoint + "/" + originalFilename;
        return Result.success(url);
    }


}

